<?php
/**
 * 圈子
 * User: liu
 * Date: 2017/3/21
 * Time: 11:24
 */

namespace Api\Controller;
use JPush\Client as JPush;
use Com\Message;
class CircleController extends ApiController
{
    /**
     * 发帖子
     */
    public function postThreads(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        $uid=API_UID;
        params_exist(array(
            'content'
        ));

        $cover_ids = I('cover_ids');
        $video_id=I('video_id');
        //is_array($cover_ids) && $cover_ids = implode(',', $cover_ids);
        if(I('video_id') == 3){
            $video_id=3;
        }

        if($cover_ids == 3){
            $cover_ids = 3;
        }

        $data = array(
            'content' =>I('content'),
            'cover_ids'=> $cover_ids,
            'video_id' => $video_id,
            'uid'       =>$uid,
            'up_time'  => NOW_TIME,
            'year'      =>date("Y"),
            'month'      =>date("m"),
            'day'      =>date("d")
        );

        $res= M('Post')->add($data);
        if($res){
            response(1,$res,'发帖成功');
        }else{
            response(-9,$res,'发帖失败');
        }
    }

    /**
     * 查看个人的动态
     */
    public  function  ownDynamic(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        $uid=I('uid');

        $list = M('post')->where('uid='.$uid)->order('up_time desc')->select();
        $today=date('Y')."-".date("m")."-".date('d');
        $t= date('d')-1;
        $yesterday=date('Y')."-".date('m')."-".$t;
        foreach ($list as $key=>&$item){
            $date=date('Y-m-d', $item['up_time']);
            if($today == $date){
                $item['up_time']="今天";
            }else if($yesterday == $date){
                $item['up_time'] ="昨天";
            }else{
                $item['up_time'] = date('Y-m-d', $item['up_time']);
            }
            $images = array();
            $images_id = str2arr($item['cover_ids'], ',');
            foreach ($images_id as $cover_id) {
                $images[] = get_url($cover_id);
            }
            if($item['cover_ids'] !=3){
                $item['is_img'] =1;
            }else  if($item['video_id'] !=3){
                $item['is_img'] = 2;
            }else{
                $item['is_img'] = null;
            }
            $item['image_path'] = $images;
            $item['thumb_image_path'] = get_url(get_movie($item['video_id'],'thumb_cover_id'));
            $config = C('UPLOAD_SITEIMG_QINIU');
            $qiniu = new  \Think\QiniuStorage($config);
            $k=get_movie($item['video_id'], 'savename');
            $movie_path=$qiniu->downlink($k);
            $item['movie_path'] =  $movie_path;
        }
        $user = M('Member')->where('uid='.$uid)->field('nickname,avatar')->find();
        $user['avatar_img']=get_cover($user['avatar'],'path');
        $data['list'] =$list;
        $data['user'] =$user;
        //是否关注
        $map['uid'] = API_UID;
        $map['to_uid'] = $uid;
        $follow = M('follow')->where($map)->find();
        if($follow){
            $data['is_follow'] = 1;
        }else{
            $data['is_follow'] = 0;
        }
        if($uid ==API_UID){
            $data['is_me'] = 1;
        }else{
            $data['is_me'] = 0;
        }

        if($list){
            response(1,$data);
        }else{
            response(-9,'','没有发表动态');
        }
    }

    /**
     * 查看全部动态
     */
    public  function  allDynamic()
    {
        $list = M('post')->order('up_time desc')->select();
        foreach ($list as $key=>&$item){
            $date=date('Y-m-d', $item['up_time']);
            $item['up_time'] =friend_date($item['up_time']);
            $images = array();
            $images_id = str2arr($item['cover_ids'], ',');
            foreach ($images_id as $cover_id) {
                $images[] = get_url($cover_id);
            }
            if($item['cover_ids'] != 3){
                $item['is_img'] =1;
            }else if($item['video_id'] !=3){
                $item['is_img'] = 2;
            }else{
                $item['is_img'] = null;
            }
            $item['image_path'] = $images;
            $item['thumb_image_path'] = get_url(get_movie($item['video_id'],'thumb_cover_id'));
            $config = C('UPLOAD_SITEIMG_QINIU');
            $qiniu = new  \Think\QiniuStorage($config);
            $k=get_movie($item['video_id'], 'savename');
            $movie_path=$qiniu->downlink($k);
            $item['movie_path'] =  $movie_path;
            //$item['movie_path'] =  mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Uploads/Movie/' . get_movie($item['video_id'], 'savepath') . get_movie($item['video_id'], 'savename');

            $user = M('Member')->where('uid='.$item['uid'])->field('nickname,avatar')->find();
            $item['avatar_img']=get_cover($user['avatar'],'path');
            $item['nickname']=$user['nickname'];
        }
        if($list){
            response(1,$list);
        }else{
            response(-9,'','没有数据');
        }
    }

    /**
     * 查看单个动态
     */
     public  function  postDetails(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);

         $uid=API_UID;
         $id = I('id');
         $info = M('post')->where('id='.$id)->order('up_time desc')->find();

         $images_id = str2arr($info['cover_ids'], ',');
         foreach ($images_id as $cover_id) {
             $images[] = get_url($cover_id);
         }
         if($info['cover_ids'] !=3){
             $info['is_img'] =1;
         }else if($info['video_id'] !=3){
             $info['is_img'] = 2;
         }else{
             $info['is_img'] = null;
         }

         $info['image_path'] = $images;
         $info['thumb_image_path'] = get_url(get_movie($info['video_id'],'thumb_cover_id'));
         $config = C('UPLOAD_SITEIMG_QINIU');
         $qiniu = new  \Think\QiniuStorage($config);
         $k=get_movie($info['video_id'], 'savename');
         $movie_path=$qiniu->downlink($k);
         $info['movie_path'] =  $movie_path;
         //$info['movie_path'] =  mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Uploads/Movie/' . get_movie($info['video_id'], 'savepath') . get_movie($info['video_id'], 'savename');


         $user = M('member')->where('uid='.$info['uid'])->find();
         $info['nickname'] = $user['nickname'];
         $info['avatar_img'] = get_cover($user['avatar'],'path');;//头像
         //是否关注
         $map['uid'] = $uid;
         $map['to_uid'] = $info['uid'];
         $follow = M('follow')->where($map)->find();
         if($follow){
             $info['is_follow'] = 1;
         }else{
             $info['is_follow'] = 0;
         }
         if($uid == $info['uid'] ){  //自己的帖子不显示关注按钮
             $info['is_follow'] = 2;
         }
         //是否点赞
         $maps['uid'] = $uid;
         $maps['con_id'] =$id;
         $maps['type'] = 1;
         $thumbs_up = M('thumbs_up')->where($maps)->find();
         if($thumbs_up){
             $info['is_thumbs_up'] = 1;
         }else{
             $info['is_thumbs_up'] = 0;
         }
         //帖子点赞数量
         $m['con_id'] =$id;
         $m['type'] = 1;
         $thumbs_up_cnt = M('thumbs_up')->where($m)->count();
         $info['thumbs_up_cnt'] =$thumbs_up_cnt;
         //帖子评论数量
         $comment_cnt = M('comment')->where('post_id='.$id)->count();
         $info['comment_cnt'] = $comment_cnt;
         //帖子评论
         $comment = M('comment')->where('post_id='.$id)->order('up_time desc')->select();
          foreach ($comment as &$com){
              $user = M('member')->where('uid='.$com['uid'])->find();
              $com['nickname'] = $user['nickname'];
              $com['avatar_img'] = get_cover($user['avatar'],'path');//头像
              $com['up_time'] = friend_date($com['up_time']);  //时间格式化
              //是否点赞
              $maps['uid']     = $uid;
              $maps['con_id']  = $com['id'];
              $maps['type']    = 2;
              $thumbs_up = M('thumbs_up')->where($maps)->find();
              if($thumbs_up){
                  $com['is_thumbs_up'] = 1;
              }else{
                  $com['is_thumbs_up'] = 0;
              }
              //评论点赞数量
              $m['con_id'] = $com['id'];
              $m['type']   = 2;
              $thumbs_up_cnt = M('thumbs_up')->where($m)->count();
              $com['thumbs_up_cnt'] =$thumbs_up_cnt;
              //回复数量
              $comment_cnt = M('reply')->where('com_id='.$com['id'])->count();
              $com['reply_cnt'] = $comment_cnt;
              //回复内容
              $reply = M('reply')->where('com_id='.$com['id'])->select();
              foreach ($reply as &$re){
                  $user = M('member')->where('uid='.$re['uid'])->find();
                  $re['nickname'] = $user['nickname'];
                  $re['avatar_img'] = get_cover($user['avatar'],'path');//头像
                  $re['up_time'] = friend_date($re['up_time']);  //时间格式化
              }
              $com['reply'] = $reply;
          }
          $data['post_content'] = $info;
          $data['comment'] =$comment;
         if($info){
             response(1,$data);
         }else{
             response(-9,'','没有找到内容');
         }
     }

    /**
     * 点赞
     * type 1 帖子点赞 2评论点赞
     */
     public function thumbs_up(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);
         params_exist(array('type','id'));
         $uid  = API_UID;
         $type = I('type');
         $id   = I('id');
         $where['uid']    = $uid;
         $where['type']   = $type;
         $where['con_id'] = $id;
         $thumbs_up = M('thumbs_up')->where($where)->find();
         $map['type']   = $type;
         $map['con_id'] = $id;
         $thumbs_cnt=0;
         if($thumbs_up){
             $res = M('thumbs_up')->where($where)->delete();
             $thumbs_cnt=M('thumbs_up')->where($map)->count();
             $is_thumbs_up=0;  //是否点赞
             $message="取消点赞";
         }else{
            $res =  M('thumbs_up')->add($where);
             $thumbs_cnt =M('thumbs_up')->where($map)->count();
             $is_thumbs_up=1;//是否点赞
             $message="点赞成功";
         }

         $data['thumbs_cnt']   = $thumbs_cnt;
         $data['is_thumbs_up'] = $is_thumbs_up;
         if($res){
             response(1,$data,$message);
         }else{
             response(-9,'','没有找到内容');
         }
     }

    /**
     * 添加评论
     */
     public  function  addcomment(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);

         params_exist(array('content','post_id'));
         $uid  = API_UID;
         if(!I('content')){
             response(-9,'','评论内容不能为空!');
         }
         $data = array('content'=>I('content'),
                        'uid'    =>$uid,
                        'post_id'=>I('post_id'),
                        'up_time'=>NOW_TIME
                        );
         $res =M('comment')->add($data);
         if($res){
             response(1,'','评论成功');
         }else{
             response(-9,'','评论失败');
         }
     }

     /**
      * 回复评论
      */
      public function  addreply(){
          !api_login() && response(-94);
          !passed_login() && response(-95);
          !only_login() && response(-96);

          params_exist(array('content','com_id'));
          $uid  = API_UID;
          if(!I('com_id')){
              response(-9,'','回复内容不能为空!');
          }
          $data = array('content'=>I('content'),
                        'uid'    =>$uid,
                        'com_id'=>I('com_id'),
                        'up_time'=>NOW_TIME
          );
          $res =M('reply')->add($data);
          if($res){
              response(1,'','回复成功');
          }else{
              response(-9,'','回复失败');
          }
      }

    /**
     * 添加关注
     */
    public  function addfollow(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        params_exist(array('to_uid'));
        $uid  = API_UID;
        $map['uid']=$uid;
        $map['to_uid']=I('to_uid');
        $result = M('follow')->where($map)->find();
        if($result){
            $res= M('follow')->where($map)->delete();
            $data['is_follow'] = 0;
            $message="取消关注";
        }else{
            $map['up_time']=NOW_TIME;
            $res = M('follow')->add($map);
            $data['is_follow'] = 1;
            $message="关注成功";
        }
        if($res){
            response(1,$data,$message);
        }else{
            response(-9,'','关注失败');
        }
    }

    /**
     * 个人关注列表
     */
    public function followList(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
         !only_login() && response(-96);

        $uid  = API_UID;
        $follow = M('follow')->where('uid='.$uid)->select();
        foreach ($follow as &$fol){
            $user = M('member')->where('uid='.$fol['to_uid'])->find();
            $fol['nickname'] = $user['nickname'];
            $fol['avatar_img'] =get_cover($user['avatar'],'path');//头像
            if(!$fol['avatar_img']){
                $fol['avatar_img']='';
            }
            $post = M('post')->where("uid=".$fol['to_uid'])->order('up_time desc')->find();
            if(strlen($post['content'])>30) {
                $fol['content'] = substr($post['content'], 0, 30) . "...";
            }else{
                $fol['content'] =$post['content'];
            }
        }
        if($follow){
            response(1,$follow);
        }else{
            $arr['time']=NOW_TIME;
            $data=array();
            $data[] = $arr;
            response(-9,$data,'你还没有关注别人');
        }
    }

    /**
     * 发起需求
     */
     public function invite(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        $uid  = API_UID;
        params_exist(array('demand',
                            'number',
                            'description',
                            'place',
                            'money',
                            'eff_time'));
        empty(I('demand')) && response('-9', '', '需求不能为空');
        empty(I('number')) && response('-9', '', '需求人数不能为空');
        empty(I('eff_time')) && response('-9', '', '有效期限不能为空');
        empty(I('description')) && response('-9', '', '详情描述不能为空');
        empty(I('place')) && response('-9', '', '邀约地点不能为空');
        empty(I('money')) && response('-9', '', '酬金不能为空');
        $time=strtotime(date("Y-m-d"));
        $eff_time=I('eff_time')+1;
        $fee = M('invite_fee')->getField('money');  //手续费
        $map =array('demand'=>I('demand'),
                    'number'=>I('number'),
                    'description'=>I('description'),
                    'place'=> I('place'),
                    'money'=> I('money'),
                    'fee'  =>$fee,
                    'uid'   => $uid,
                    'eff_time'=> I('eff_time'),
                    'end_date' => strtotime('+ '.$eff_time.' day',$time),
                    'pay_status'=>0,
                    'up_time' => NOW_TIME);
        $res = M('invite')->add($map);
        if($res){
            $data['invite_id'] =$res;
            $data['money'] = $fee;
            response(1,$data,'发布需求成功');
        }else{
            response(-9,'','发布需求失败');
        }
    }

    /**
     * 支付邀约酬金订单
     *type  充值方式支付宝
     * @param  amount
     */
    public function rechargeOrder(){

        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);

        params_exist(array('invite_id'));
        $invite = M('invite')->where('id='.I('invite_id'))->find();
        if($invite){
            $fee = M('invite_fee')->getField('money');
        }else{
            response('-9','','没有查到发布的需求');
        }
        $data = array(
            'uid'       =>  API_UID,
            'order_no' => build_order_no(),
            'amount'   => $fee,
            'status'   => 0,
            'create_time' => NOW_TIME,
            'invite_id'   =>I('invite_id'),
            'type'         => 1
        );
        $recharge = M('recharge_order');

        $InsertId   = $recharge->add($data);
        if ($InsertId){
            response(1,array('order_no'=>$data['order_no'],'amount'=>$fee));
        }else{
            response(-9);
        }
    }

    /**
     * 查看全部邀约
     */
    public function inviteList(){

        $time=NOW_TIME;
        $maps['end_date'] =array('gt',$time);
        $maps['pay_status'] = 1;
        $list = M('invite')->where($maps)->order('up_time desc')->select();
        $data = array();

        foreach($list as $key=>&$li){
            $where['inv_id'] =$li['id'];
            $where['status'] =1;
            $cnt =M('invited_to')->where($where)->count();//同意邀约人数
            $map['id'] =$li['id'];
            $map['pay_status'] = 1;
            $map['number']=array('egt',$cnt);
            $info = M('invite')->where($map)->find();  //判断是否满足应邀人数
            if($info){
                $data[$key]['id'] = $info['id'];
                $data[$key]['demand']=$info['demand'];
                $data[$key]['number']=$info['number'];
                $data[$key]['description']= $info['description'];
                $data[$key]['place']=$info['place'];
                $data[$key]['money']=$info['money'];

                $user = M('member')->where('uid=' . $info['uid'])->find();
                $data[$key]['nickname'] = $user['nickname'];
                $data[$key]['avatar_img'] = get_cover($user['avatar'], 'path');//头像
                $data[$key]['ying_cnt'] = M('invited_to')->where('inv_id=' . $info['id'])->count();
                $end_date = strtotime('- 1 day', $info['end_date']);
                $data[$key]['end_date'] = date('Y-m-d', $end_date);
            }
        }
        if($data){
            response(1,$data);
        }else{
            response(-9,'','没有邀约');
        }
    }

    /**
     * 获取应邀弹出页
     */
    public function invitepage(){
        params_exist(array('inv_id'));
        $inv_id=I('inv_id');
        $res = M('invite')->where('id='.$inv_id)->find();
        $end_date = strtotime('- 1 day',$res['end_date']);
        $res['end_date'] =date('Y-m-d', $end_date);
        $user = M('member')->where('uid='.$res['uid'])->find();
        $res['nickname'] = $user['nickname'];
        $res['avatar_img']=get_cover($user['avatar'],'path');//头像
        if($res){
            response(1,$res);
        }else {
            response(-9);
        }

    }

    /**
     * 添加应邀
     * type 1 应邀 2匿名应邀
     */
     public  function  addinvite(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);

         params_exist(array('inv_id','type'));
         $type=I('type');
         $uid=API_UID;

         $data = array('inv_id'=>I('inv_id'),
                        'content'=>I('content'),
                        'uid'     =>$uid,
                        'status'  => 0,
                        'up_time' => NOW_TIME,
                        'anonymity'=>$type
                      );
         $res = M('invited_to')->add($data);

         if($res){
             response(1,$res,'申请应邀成功');
         }else{
             response(-9,'','申请应邀失败');
         }
     }

    /**
     * 邀约详情
     */
     public function inviteDetails(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);
         $uid=API_UID;

         $inv_id=I('inv_id');
         $info = M('invite')->where('id='.$inv_id)->find();
         $end_date = strtotime('- 1 day',$info['end_date']);
         $info['end_date'] = date('Y-m-d', $end_date);
         $user = M('member')->where('uid='.$info['uid'])->find();
         $info['nickname'] = $user['nickname'];
         $info['avatar_img']=get_cover($user['avatar'],'path');//头像

         $cnt =M('invited_to')->where('inv_id='.$inv_id)->count();//已应邀人数
         $info['ying_cnt'] = $cnt;
         $maps['inv_id'] =$inv_id;
         $res = M('invited_to')->where($maps)->select();
         $map['uid']=$uid;
         $map['inv_id']=$inv_id;
         //是否是自己发布的邀约
         if($uid == $info['uid']){
             $info['is_own'] = 1;
         }else{
             $info['is_own'] = 0;
         }
         $r = M('invited_to')->where($map)->find();
         //是否应邀过
         if($r){
            $info['is_invite'] = 1;
         }else{
             $info['is_invite'] = 0;
         }
         foreach ($res as &$r){
             //是否匿名
             if($r['anonymity'] ==1) {
                 $user = M('member')->where('uid=' . $r['uid'])->find();
                 $r['nickname'] = $user['nickname'];
                 $r['avatar_img'] = get_cover($user['avatar'], 'path');//头像
                 $r['is_name']=1;
             }else if($r['anonymity'] ==2){
                $r['nickname']='某某';
                $r['avatar_img'] ='';
                $r['is_name'] = 2;
             }
         }
         $data['detail']=$info;
         $data['ying_list']=$res;
         if($info){
             response(1,$data);
         }else{
             response(-9);
         }
     }

    /**
     * 选择应邀人
     */
     public  function  choiceInvite(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
         $uid=API_UID;
         $inv_to_id=I('id');
         $res = M('invited_to')->where('id='.$inv_to_id)->find();
         $user_inv_to = M('member')->where('uid='.$res['uid'])->find(); //应邀人
         $uaername_inv =M('Ucenter_member')->where('id='.$res['uid'])->getField('username');
         $user_inv = M('member')->where('uid='.$uid)->find(); //发起需求的人
         $invite = M('invite')->where('id='.$res['inv_id'])->find();
         $inv_name = $user_inv['nickname'];
         $inv_to_name = $user_inv_to['nickname'];
         $place= $invite['place'];
         $demand=$invite['demand'];
         $content = $inv_name.'在'.$place.'地点'.'邀请您'.$demand;

         $data = array('inv_to_id'=>$inv_to_id,
                      'content'=>$content,
                      'uid'=>$uid,
                      'up_time'=>NOW_TIME
                 );
         $pid= M('push_log')->add($data);

         //Vendor('jpush-api-php.src.JPush.Client');
        // $client = new  Jpush($this->app_key, $this->master_secret);
         $title = '小元';

        // $content = $inv_name.'邀请您'.$demand;

        $flag=  R('Push/pushOrder',array($title,$content,$uaername_inv,'',$inv_to_id));
         $flag=0;
         // 推送成功 更改状态
         if ($flag)
         {
             $pid= M('push_log')->where('id='.$pid)->setField('is_push',1);
         }
         response(1,'','推送成功');
     }

     /**
      * 是否同意邀请
      */
     public function   whetherAgree(){
         !api_login() && response(-94);
         !passed_login() && response(-95);
         !only_login() && response(-96);
         $uid= API_UID;
         $type=I('type');
         $inv_to_id=I('inv_to_id');
         $res = M('invited_to')->where('id='.$inv_to_id)->find();
         if(!$res){
             response(-9,'','没有找到应邀');
         }
         $invite = M('invite')->where('id='.$res['inv_id'])->find();
         $invite_to_id_iphone=M('Ucenter_member')->where('id='.$res['uid'])->getField('username'); //应邀人
         $invite_to_id_name=M('member')->where('uid='.$res['uid'])->getField('nickname'); //应邀人

         $invite_iphone=M('Ucenter_member')->where('id='.$invite['uid'])->getField('username');//发起应邀的人
         $invite_name=M('member')->where('uid='.$invite['uid'])->getField('nickname');//发起应邀的人

         $demand = $invite['demand'];
         if($type==1){ //同意
             $flg=M('invited_to')->where('id='.$inv_to_id)->setField('status',1);
             $str="#name#=您&#othername#=".$invite_name.$demand."&#place#=".$invite['place']."&#iphone#=".$invite_iphone;
             $str2="#name#=".$invite_to_id_name."&#othername#=您的".$demand."&#place#=".$invite['place']."&#iphone#=".$invite_to_id_name;
             Message::send($invite_to_id_iphone,$str,'30933');
             Message::send($invite_iphone,$str2,'30933');
             response(1,'','同意邀请');
         }else if($type==2){ //拒绝
             $flg=M('invited_to')->where('id='.$inv_to_id)->setField('status',2);
             $str2="#name#=".$invite_name."&#othername#=您的".$demand."&#place#=".$invite['place']."&#iphone#=".$invite_iphone;
             Message::send($invite_to_id_iphone,$str2,'30975');
             response(2,'','拒绝邀请');
         }
     }




}